<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2016-10-22
 * Time: 10:27
 */

namespace app\src\profit\action;




use app\src\accountScore\action\AccountScoreAction;
use app\src\accountScore\logic\AccountScoreLogic;

use app\src\base\action\BaseAction;
use app\src\consumehistory\logic\ConsumeHistoryLogic;
use app\src\filiation\logic\FiliationLogic;
use app\src\platform\logic\PlatformLogic;
use app\src\powersystem\enum\AdminRoleEnum;
use app\src\powersystem\logic\AuthGroupAccessLogic;
use app\src\profit\enum\ProfitEnum;
use app\src\profit\logic\ProfitLogic;
use app\src\seller\helper\OrderCodeHelper;
use app\src\seller\logic\SellerLogic;
use app\src\seller\logic\SellerOrderLogic;
use think\Db;

class ProfitAction extends BaseAction{

    /*
     * 查询一笔消费，获利人
     * type1保险  2普通消费
     * uid 消费发起人
     * amount 消费金额,保险不需要
     */
    public function dealProfit($type,$uid,$amount=0,$order_id){

        //判断是不是第一消费，走不走分佣流程
        if($type==ProfitEnum::SELLER_TYPE) {
            $isFirst = $this->isFirst($type,$uid,$order_id);
            //if(!$isFirst) return $this->error('处理出错');
            if($isFirst){
                $orderps = $this->orderps($order_id,true);
                if(!$orderps['status']) return $this->error('处理出错');
                return $this->success('第一次不处理');
            }
        }
        //重复性检测
        $isRepeat = (new ProfitLogic())->getInfo(['uid'=>$uid,'order_id'=>$order_id,'type'=>$type]);
        $seller_order = (new SellerOrderLogic())->getInfo(['id'=>$order_id]);
        $seller_id = $seller_order['info']['seller_id'];
        if($isRepeat['status']){
            if(!empty($isRepeat['info'])){
                return $this->success('已处理');
            }
        }else{
            return $this->error('查询出错');
        }
        $seller = (new SellerLogic())->getInfo(['id'=>$seller_id]);
        $rack_back_rate = $seller['info']['rack_back_rate'];
        $money = $amount*$rack_back_rate;
        $profit = [];
        if($type==ProfitEnum::INSURANCE_TYPE){
            $profit = $this->InsuranceProfit($uid,'10000');
            $money = '10000';
        }elseif($type==ProfitEnum::SELLER_TYPE){
            $profit = $this->SellerProfit($uid,$money,$seller_id);
            if(!$profit['status'])return $this->error($profit['info']);
        }
        if($profit['status']){
            //处理收益
            $profit=$profit['info'];
            $p1_3=$this->dealEntity($type,$profit);

            $p1_3=$p1_3['info'];
            $entity=[
                'p0'=>$p1_3['p0'],
                'p1'=>$p1_3['p1'],
                'p1_5'=>$p1_3['p1_5'],
                'p2'=>$p1_3['p2'],
                'p3'=>$p1_3['p3'],
                'p4'=>$profit['profit']['person'],
                'p5'=>$profit['profit']['city'],
                'p6'=>$profit['profit']['province'],
                'p7'=>0,
                's0'=>$p1_3['s0'],
                's1'=>$p1_3['s1'],
                's1_5'=>$p1_3['s1_5'],
                's2'=>$p1_3['s2'],
                's3'=>$p1_3['s3'],
                's4'=>$profit['money']['person'],
                's5'=>$profit['money']['city'],
                's6'=>$profit['money']['province'],
                's7'=>$profit['money']['headquarters'],
                'surplus'=>$money-$p1_3['s0']-$p1_3['s1']-$p1_3['s1_5']-$p1_3['s2']-$p1_3['s3']-$profit['money']['person']-$profit['money']['city']-$profit['money']['province']-$profit['money']['headquarters'],
                'uid'=>$uid,
                'type'=>$type,
                'order_id'=>$order_id,
                'create_time'=>NOW_TIME
            ];
            $profit_add = (new ProfitLogic())->add($entity);
            $account_score = (new AccountScoreAction())->dealBuy($entity);
            if(!$account_score['status']) return $this->error($account_score['info']);
            $orderps = $this->orderps($order_id,false);
            if(!$orderps['status']) return $this->error('处理出错');
            return $this->success($profit_add['info']);
        }else{
            return $this->error($profit['info']);
        }
    }
    //查车险的获利人
    public function InsuranceProfit($uid,$amount){
        $rate = ProfitEnum::getProfitRate();
        $rate = $rate['INSURANCE'];
        $filiation=(new FiliationLogic())->getInfo(['uid'=>$uid]);

        if(!empty($filiation['info'])){
            $father_id = $filiation['info']['p1'];
            $seller_id = $filiation['info']['p2'];
            $person = $filiation['info']['p3'];
            $city = $filiation['info']['p4'];
            $province = $filiation['info']['p5'];


            if(empty($father_id)&&!empty($seller_id)){
                //若此人没有被个人推荐，而是被商家直接推荐
                //个创-》商家-》本人
                //判断此商家是否有店小二
                $seller = (new SellerLogic())->getInfo(['id'=>$seller_id]);
                if(empty($seller['info'])) return $this->error('找不到店铺');
                if(empty($seller['info']['waiter_id'])){
                    //没有店小二的情况
                    $profit['seller'] = $seller_id;
                    $discount['seller'] = $rate['IN_STORE']+$rate['IN_STOREKEEPER'];
                }else{
                    //有店小二的情况
                    $profit['seller'] = $seller_id;
                    $discount['seller'] = $rate['IN_STORE'];
                    $profit['waiter'] = $seller['info']['waiter_id'];
                    $discount['waiter'] = $rate['IN_STOREKEEPER'];
                }
                $flag = 2;
            }elseif(!empty($father_id)){
                //若此人被个人推荐，而不是被商家直接推荐
                //个创-》会员-》本人or个创-》商户-》会员-》本人or个创-》商户-》会员-》会员-》本人
                $profit['father'] = $filiation['info']['p1'];
                $discount['father'] = $rate['IN_MEMBER'];
                $flag = 3;
            }elseif(empty($father_id)&&empty($seller_id)){
                //此人被个创推荐
                //个创-》本人
                $flag = 1;
            }
            $profit['me'] = $uid;
            $discount['me'] = 0;
            $profit['person'] = $person;
            $discount['person'] = $rate['IN_PERSON'];
            $profit['city'] = $city;
            $discount['city'] = $rate['IN_CITY'];
            $profit['province'] = $province;
            $discount['province'] = $rate['IN_PROVINCE'];

            foreach($discount as $k=>$v){
                $key = $k;
                $money[$k] = $v*$amount;
            }
            $discount['headquarters'] = $rate['IN_HEADQUARTERS'];
            $money['headquarters'] = $amount*$rate['IN_HEADQUARTERS'];

            return $this->success(['profit'=>$profit,'discount'=>$discount,'money'=>$money,'flag'=>$flag]);

        }else{
            return $this->error('找不到发起人的获利信息');
        }
    }
    //查普通消费的获利人
    public function SellerProfit($uid,$amount,$seller_id_buy){
        $rate = ProfitEnum::getProfitRate();
        $rate = $rate['SELLER'];
        $filiation=(new FiliationLogic())->getInfo(['uid'=>$uid]);


        if(!empty($filiation['info'])){
            $father_id = $filiation['info']['p1'];
            $grand_father_id = $filiation['info']['p1_5'];


            $seller_id = $filiation['info']['p2'];
//            $person = $filiation['info']['p3'];
//            $city = $filiation['info']['p4'];
//            $province = $filiation['info']['p5'];
            $seller_filiation = (new SellerLogic())->getInfo(['id'=>$seller_id_buy]);
            if(!$seller_filiation['status']||empty($seller_filiation['info'])) return $this->error('找不到商家关系');
            $person = $seller_filiation['info']['parent_id'];
            $person_filiation = (new PlatformLogic())->getInfo(['id'=>$person]);
            if(!$person_filiation['status']||empty($person_filiation['info'])) return $this->error('找不到个人关系');
            $city = $person_filiation['info']['parent_id'];
            $city_filination = (new PlatformLogic())->getInfo(['id'=>$city]);

            if(!$city_filination['status']) return $this->error('找不到市级关系');
            if(empty($city_filination['info'])) return $this->error('找不到市级关系');
            $province = $city_filination['info']['parent_id'];

            $seller = (new SellerLogic())->getInfo(['id'=>$seller_id]);
            if(empty($seller['info'])){
                $waiter_id = 0;
            }else{
                $waiter_id = $seller['info']['waiter_id'];
            }

            $flag = 0;
            if(empty($father_id)&&empty($grand_father_id)){
                if(empty($seller_id)){
                    //推荐链：个创-》本人
                    //TODO
                    $flag = 1;

                }else{
                    //个创-》商家-》本人
                    $profit['seller'] = $seller_id;
                    $discount['seller'] = $rate['SE_FA_STORE'];
                    if(!empty($waiter_id)){
                        $profit['waiter'] = $waiter_id;
                        $discount['waiter'] = $rate['SE_STOREKEEPER'];
                    }
                    $flag = 3;
                }
            }elseif(!empty($father_id)&&empty($grand_father_id)){
                if(empty($seller_id)){
                    //个创-》会员-》本人
                    $profit['father'] = $father_id;
                    $discount['father'] = $rate['SE_FA_MEMBER'];
                    $flag = 2;
                }else{
                    //个创-》商家--》会员--》本人
                    $profit['father'] = $father_id;
                    $discount['father'] = $rate['SE_FA_MEMBER'];
                    $profit['seller'] = $seller_id;
                    $discount['seller'] = $rate['SE_GFA_STORE'];
                    if(!empty($waiter_id)){
                        $profit['waiter'] = $waiter_id;
                        $discount['waiter'] = $rate['SE_STOREKEEPER'];
                    }
                    $flag = 5;
                }

            }elseif(!empty($father_id)&&!empty($grand_father_id)){
                //个创-》商家-》会员-》会员-》本人
                $profit['father'] = $father_id;
                $discount['father'] = $rate['SE_FA_MEMBER'];
                $profit['grand_father'] = $grand_father_id;
                $discount['grand_father'] = $rate['SE_GFA_MEMBER'];
                $flag = 4;
            }




            $profit['person'] = $person;
            $discount['person'] = $rate['SE_PERSON'];
            $profit['city'] = $city;
            $discount['city'] = $rate['SE_CITY'];
            $profit['province'] = $province;
            $discount['province'] = $rate['SE_PROVINCE'];
            $profit['me'] = $uid;
            $discount['me'] = $rate['SE_ME'];


            foreach($discount as $k=>$v){
                $key = $k;
                $money[$k] = $v*$amount;
            }
            $discount['headquarters'] = $rate['SE_HEADQUARTERS'];
            $money['headquarters'] = $amount*$rate['SE_HEADQUARTERS'];
            return $this->success(['profit'=>$profit,'discount'=>$discount,'money'=>$money,'flag'=>$flag]);

        }else{
            return $this->error('找不到发起人的获利信息');
        }
    }

    /*
     * 收益处理完，进行分钱前置处理
     */
    public function dealEntity($type,$info){
        $flag=$info['flag'];
        $array=[];
        if($type==ProfitEnum::INSURANCE_TYPE){
            //若是保险
            if($flag==1){
                //个创-》本人
                $array=[
                    'p0'=>$info['profit']['me'],'s0'=>0,
                    'p1'=>0,'p1_5'=>0,'p2'=>0,'p3'=>0,'s1'=>0,'s1_5'=>0,'s2'=>0,'s3'=>0];
            }elseif($flag==2){
                //个创-》商家-》本人
                if(!empty($info['profit']['waiter'])){
                    //存在店小二
                    $array=[
                        'p0'=>$info['profit']['me'],'s0'=>0,
                        'p1'=>0,'s1'=>0,
                        'p1_5'=>0,'s1_5'=>0,
                        'p2'=>$info['profit']['seller'],'s2'=>$info['money']['seller'],
                        'p3'=>$info['profit']['waiter'],'s3'=>$info['money']['waiter']
                    ];
                }else{
                    //不存在店小二
                    $array=[
                        'p0'=>$info['profit']['me'],'s0'=>0,
                        'p1'=>0,'s1'=>0,
                        'p1_5'=>0,'s1_5'=>0,
                        'p2'=>$info['profit']['seller'],'s2'=>$info['money']['seller'],
                        'p3'=>0,'s3'=>0
                    ];
                }
            }elseif($flag==3){
                //个创-》会员-》本人
                $array=[
                    'p0'=>$info['profit']['me'],'s0'=>0,
                    'p1'=>$info['profit']['father'],'s1'=>$info['money']['father'],
                    'p1_5'=>0,'s1_5'=>0,
                    'p2'=>0,'s2'=>0,
                    'p3'=>0,'s3'=>0
                ];
            }
            return $this->success($array);
        }elseif($type==ProfitEnum::SELLER_TYPE){
            //若是商户消费
            if($flag==1){
                //推荐链：个创-》本人
                $array=[
                    'p0'=>$info['profit']['me'],'s0'=>$info['money']['me'],
                    'p1'=>0,'p1_5'=>0,'p2'=>0,'p3'=>0,'s1'=>0,'s1_5'=>0,'s2'=>0,'s3'=>0];
            }elseif($flag==2){
                //个创-》会员-》本人
                $array=[
                    'p0'=>$info['profit']['me'],'s0'=>$info['money']['me'],
                    'p1'=>$info['profit']['father'],'s1'=>$info['money']['father'],
                    'p1_5'=>0,'s1_5'=>0,
                    'p2'=>0,'s2'=>0,
                    'p3'=>0,'s3'=>0
                ];
            }elseif($flag==3){
                //个创-》商家-》本人
                if(!empty($info['profit']['waiter'])){
                    //存在店小二
                    $array=[
                        'p0'=>$info['profit']['me'],'s0'=>$info['money']['me'],
                        'p1'=>0,'s1'=>0,
                        'p1_5'=>0,'s1_5'=>0,
                        'p2'=>$info['profit']['seller'],'s2'=>$info['money']['seller'],
                        'p3'=>$info['profit']['waiter'],'s3'=>$info['money']['waiter']
                    ];
                }else{
                    $array=[
                        'p0'=>$info['profit']['me'],'s0'=>$info['money']['me'],
                        'p1'=>0,'s1'=>0,
                        'p1_5'=>0,'s1_5'=>0,
                        'p2'=>$info['profit']['seller'],'s2'=>$info['money']['seller'],
                        'p3'=>0,'s3'=>0
                    ];
                }

            }elseif($flag==4){
                //个创-》（商家-》）会员-》会员-》本人
                $array=[
                    'p0'=>$info['profit']['me'],'s0'=>$info['money']['me'],
                    'p1'=>$info['profit']['father'],'s1'=>$info['money']['father'],
                    'p1_5'=>$info['profit']['grand_father'],'s1_5'=>$info['money']['grand_father'],
                    'p2'=>0,'s2'=>0,
                    'p3'=>0,'s3'=>0
                ];
            }elseif($flag==5){
                //个创-》商家--》会员--》本人
                if(!empty($info['profit']['waiter'])){
                    //存在店小二
                    $array=[
                        'p0'=>$info['profit']['me'],'s0'=>$info['money']['me'],
                        'p1'=>0,'s1'=>0,
                        'p1_5'=>0,'s1_5'=>0,
                        'p2'=>$info['profit']['seller'],'s2'=>$info['money']['seller'],
                        'p3'=>$info['profit']['waiter'],'s3'=>$info['money']['waiter']
                    ];
                }else{
                    $array=[
                        'p0'=>$info['profit']['me'],'s0'=>$info['money']['me'],
                        'p1'=>$info['profit']['father'],'s1'=>$info['money']['father'],
                        'p1_5'=>0,'s1_5'=>0,
                        'p2'=>$info['profit']['seller'],'s2'=>$info['money']['seller'],
                        'p3'=>0,'s3'=>0
                    ];
                }
            }
            return $this->success($array);
        }
    }

    /*
     * 判断是否第一次消费
     */

    public function isFirst($type,$uid,$order_id){
        if($type == 1){
            //若为车险订单，则不判断是否为第一次
            return false;
        }else{

            $result = (new SellerOrderLogic())->count(['uid'=>$uid,'order_status'=>1]);
            if(!$result['status']) return $this->error($result['info']);
            if($result['info']>1){
                return false;
            }else{
                return true;
            }
        }
    }


    /*
     * 将商家实收金额补充进表
     */
    public function orderps($order_id,$is_first){
        $order = (new SellerOrderLogic()) ->getInfo(['id'=>$order_id]);
        $order = $order['info'];
        $seller = (new SellerLogic())->getInfo(['id'=>$order['seller_id']]);
        $price = $order['price'];
        $amount = $order['amount'];
        $discount = $order['no_discount'];
        $income = 0;
        if($seller['info']['lock_first_offer']==1) $is_first = false;
        if($is_first){
            //若为首次消费
            $first_offer = $seller['info']['first_offer'];
            if($amount == $price){
                $income = $amount*0.994;
            }else{
                $income = $price*0.994+$first_offer;
            }

            if($seller['info']['first_offer_num']>0){
                $first_offer_num = $seller['info']['first_offer_num']-1;
                $offer = (new SellerLogic())->saveByID($order['seller_id'],['first_offer_num'=>$first_offer_num]);
            }

        }
        if(!$is_first){
            //若不是首次消费
            $rack_back_rate = $seller['info']['rack_back_rate'];
            $discount_chance = 1-($rack_back_rate+0.006);
            if($discount_chance<0) $discount_chance = 0.994;
            $price_chance = 0.994;
            $income = $discount*$price_chance + ($price-$discount)*$discount_chance;
        }
        $order_ps = (new SellerOrderLogic()) ->save(['id'=>$order_id],['income'=>$income]);
        if($order_ps['status']){
            return $this->success('success');
        }else{
            return $this->error($order_ps['info']);
        }
    }

}